package com.m4f.city.business.service.impl;

import java.util.logging.Logger;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.m4f.city.business.domain.InternalUser;
import com.m4f.city.business.service.ifc.ApiService;
import com.m4f.city.business.service.ifc.UserService;
import com.m4f.gaeweb.business.service.impl.DAOBaseService;
import com.m4f.gaeweb.persistence.dao.ifc.DAOSupport;

public class ApiServiceImpl extends DAOBaseService implements ApiService {
	
	private static final Logger LOGGER = Logger.getLogger(ApiServiceImpl.class.getName());
	private UserService userService;
	
	public ApiServiceImpl(DAOSupport dao) {
		super(dao);
	}
	
	public ApiServiceImpl(DAOSupport dao, UserService userService) {
		this(dao);
		this.userService = userService;
	}

	@Override
	public InternalUser getUserInfo() throws Exception {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication.getPrincipal() instanceof UserDetails) {
			UserDetails details = (UserDetails) authentication.getPrincipal();
			String username = details.getUsername();
			InternalUser userInternal = this.userService.getUser(username);
			return userInternal;
		} else {
			throw new BadCredentialsException("Bad credentials: not a username/password authentication.");
	    }
	}
}